package com.yc.backstage.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.backstage.common.constant.UserConstants;
import com.yc.backstage.common.service.JwtTokenServiceImpl;
import com.yc.backstage.entity.LoginUser;
import com.yc.backstage.entity.SysRole;
import com.yc.backstage.entity.vo.QueryRoleVo;
import com.yc.backstage.service.SysPermissionService;
import com.yc.backstage.service.SysRoleService;
import com.yc.backstage.service.SysUserService;
import com.yc.backstage.utils.SecurityUtils;
import com.yc.common.enums.BusinessType;
import com.yc.common.res.ResultClass;
import com.yc.common.utils.StringUtils;
import com.yc.logging.annotation.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.token.TokenService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @Classname SysRoleController
 * @Description
 * @Version 1.0.0
 * @Date 2022-08-23 11:49:19
 * @Created by Mikechen
 */
@RestController
@RequestMapping("/backstage/sysRole")
public class SysRoleController {
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysPermissionService sysPermissionService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private JwtTokenServiceImpl tokenService;

    /**
     * 获取角色列表（分页）(按条件)
     */
    @PreAuthorize("@el.hasPermi('system:user:query')")
    @GetMapping("/list")
    public ResultClass list(QueryRoleVo role) {
        Page<SysRole> sysRolePage = sysRoleService.selectPage(role);
        return ResultClass.success(sysRolePage);
    }

    /**
     * 新增角色
     */
    @PreAuthorize("@el.hasPermi('system:role:add')")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public ResultClass add(@Validated @RequestBody SysRole role) {
        if (UserConstants.NOT_UNIQUE.equals(sysRoleService.checkRoleNameUnique(role))) {
            return ResultClass.fail("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(sysRoleService.checkRoleKeyUnique(role))) {
            return ResultClass.fail("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(SecurityUtils.getUsername());
        return ResultClass.success(sysRoleService.insertRole(role));
    }

    /**
     * 根据角色编号获取详细信息
     */
    @PreAuthorize("@el.hasPermi('system:role:query')")
    @GetMapping(value = "/{roleId}")
    public ResultClass getInfo(@PathVariable Long roleId) {
        sysRoleService.checkRoleDataScope(roleId);
        return ResultClass.success(sysRoleService.selectRoleById(roleId));
    }

    /**
     * 修改保存角色
     */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResultClass edit(@Validated @RequestBody SysRole role) {
        sysRoleService.checkRoleAllowed(role);
        sysRoleService.checkRoleDataScope(role.getRoleId());
        if (UserConstants.NOT_UNIQUE.equals(sysRoleService.checkRoleNameUnique(role))) {
            return ResultClass.fail("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(sysRoleService.checkRoleKeyUnique(role))) {
            return ResultClass.fail("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(SecurityUtils.getUsername());

        if (sysRoleService.updateRole(role) > 0) {
            // 更新缓存用户权限
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin()) {
                loginUser.setPermissions(sysPermissionService.getMenuPermission(loginUser.getUser()));
                loginUser.setUser(sysUserService.selectUserByUserName(loginUser.getUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return ResultClass.success();
        }
        return ResultClass.fail("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }
}
